package net.xisberto.bustime;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.xisberto.bustime.control.SQLiteResourceDatabase;
import net.xisberto.bustime.model.Bus;
import net.xisberto.bustime.model.Record;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

public class ViewRecordsActivity extends CustomActivity implements OnClickListener {
	private SQLiteResourceDatabase db;
	private int view_type = 0;
	private int bus_id = 0;
	private ArrayList<String> group_names;
	private ArrayList<Record> records;


	private void dialogChooseViewType() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.text_view_types);
		builder.setItems(R.array.view_types, this);
		builder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				finish();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.title.setText(R.string.title_view_records);
		dialogChooseViewType();
		setContentView(R.layout.view_record_list);
		
		db = new SQLiteResourceDatabase(this);
		try {
			db.createDataBase();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == BusTimeActivity.REQUEST_VIEW_RECORD) {
			if (resultCode == RESULT_OK) {
				bus_id = data.getIntExtra(BusTimeActivity.BUS_ID, 0);
				Log.i(getApplicationContext().getPackageName(), String.valueOf("Ônibus selecionado: "+bus_id));
				db.openDataBase();
				Bus bus = db.getBus(bus_id);
				db.close();
				group_names = new ArrayList<String>();
				group_names.add(bus.getName());
				populateList();
				ExpandableListView list = (ExpandableListView) findViewById(R.id.expandable_list);
				list.expandGroup(0);
			} else {
				this.finish();
			}
		}
	}
	
	private void populateList() {
		ExpandableListView list = (ExpandableListView) findViewById(R.id.expandable_list);
		SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(this,
				createGroupList(),
				android.R.layout.simple_expandable_list_item_1,
				new String[] {"bus_name"},
				new int[] {android.R.id.text1},
				createChildList(),
				R.layout.view_record_list_item,
				new String[] {"time", "details"},
				new int[] {R.id.text1, R.id.text2});
		list.setAdapter(adapter);
		TextView text = (TextView) findViewById(R.id.empty_list);
		text.setText(R.string.activity_list_empty);
	}
	
	private List<HashMap<String, String>> createGroupList() {
		ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
		for (String group_name: group_names) {
			HashMap<String, String> m = new HashMap<String, String>();
			m.put("bus_name", group_name);
			result.add(m);
		}
		return result;
	}
	
	private List<ArrayList<HashMap<String, String>>> createChildList() {
		ArrayList<ArrayList<HashMap<String, String>>> result = new ArrayList<ArrayList<HashMap<String, String>>>();
		db.openDataBase();
		for (String group_name : group_names) {
			//Build a ArrayList for each bus (secList).
			switch (view_type) {
			case 0:
				records = db.listRecordsByBusName(group_name);
				break;
			case 1:
				records = db.listRecordsByTime(new Date().getTime());
				break;
			case 2:
				records = db.listRecordsByBusName(group_name);
			default:
				records = db.listRecordsByBusName(group_name);
				break;
			}
			 
			ArrayList<HashMap<String, String>> secList = new ArrayList<HashMap<String, String>>();
			for (Record record : records) {
				HashMap<String, String> child = new HashMap<String, String>();
				Date date = new Date(record.getTime());
				//Date format from ISO 8601
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
				String time = sdf.format(date);
				//String time = new Date(record.getTime()).toLocaleString();
				String details = "Lat: "+record.getLatitude()+"\nLong: "+record.getLongitude();
				child.put("time", time);
				child.put("details", details);
				secList.add(child);
			}
			result.add(secList);
		}
		db.close();
		return result;
	  }

	@Override
	public void onClick(DialogInterface dialog, int item) {
		view_type = item;
		db.openDataBase();
		Log.i(getApplicationContext().getPackageName(), "Item selecionado: "+item);
		switch (view_type) {
		case 0:
			group_names = db.listRecordBuses();
			populateList();
			break;
		case 1:
			//Gets time 15 minutes before now
			//TODO let user configure how much minutes
			Calendar now = Calendar.getInstance();
			now.setTimeInMillis(now.getTimeInMillis()-1000*60*15);
			ArrayList<Long> times = db.listRecordTimes();
			group_names = new ArrayList<String>();
			for (Long time : times) {
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(time);
				//Add to group_names only if time is after now
				if ((cal.get(Calendar.HOUR_OF_DAY) >= now.get(Calendar.HOUR_OF_DAY)) &&
						(cal.get(Calendar.MINUTE) > now.get(Calendar.MINUTE))) {
					group_names.add(String.format("%d:%d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)));
				}
			}
			populateList();
			break;
		case 2:
			Intent intent = new Intent(this, PersonalListActivity.class);
			intent.putExtra(BusTimeActivity.REQUEST_CODE, BusTimeActivity.REQUEST_VIEW_RECORD);
			startActivityForResult(intent, BusTimeActivity.REQUEST_VIEW_RECORD);
			break;
		default:
			this.finish();
			break;
		}
		db.close();
	}

}
